﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace Entity
{
    /// <summary>
    /// IQueryable扩展方法：条件过滤与排序功能
    /// Modify Date:2012-10-8
    /// Modify Memo:添加了动态排序功能
    /// </summary>
    public static class LinqEntity
    {
        /// <summary>
        /// 获取对应的字段名
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="keySelector"></param>
        /// <returns></returns>
        public static string GetMemberName<TSource, TKey>(Expression<Func<TSource, TKey>> keySelector)
        {
            string fieldName = null;
            var exp = keySelector.Body as UnaryExpression;
            if (exp == null)
            {
                var body = keySelector.Body as MemberExpression;
                fieldName = body.Member.Name;
            }
            else
            {
                fieldName = (exp.Operand as MemberExpression).Member.Name;
            }
            return fieldName;
        }

        /// <summary>
        /// linq结果集根据PredicateList条件构造者去过滤集合,并进行排序
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="linq">集合</param>
        /// <param name="predicateList">过滤</param>
        /// <param name="orderBy">排序</param>
        /// <returns></returns>
        public static IQueryable<TEntity> LinqForPredicate<TEntity>(this IQueryable<TEntity> linq, PredicateList<TEntity> predicateList, Action<Orderable<TEntity>> orderBy) where TEntity : class
        {
            if (predicateList != null)
            {
                if (predicateList.Count() > 0)
                    predicateList.ToList().ForEach(i =>
                    {
                        linq = linq.Where(i);
                    });
            }
            if (orderBy != null)
            {
                var orderable = new Orderable<TEntity>(linq);
                orderBy(orderable);
                return orderable.Queryable;
            }
            else
                return linq;
        }
        /// <summary>
        /// linq结果集根据PredicateList条件构造者去过滤集合
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="linq">集合</param>
        /// <param name="predicateList">过滤</param>
        /// <returns></returns>
        public static IQueryable<TEntity> LinqForPredicate<TEntity>(this IQueryable<TEntity> linq, PredicateList<TEntity> predicateList) where TEntity : class
        {
            return LinqForPredicate<TEntity>(linq, predicateList, null);
        }
    }
}
